<?php

class ActionPending_List extends BaseAction
{
    public function run()
    {
        if ( Yii::app()->request->getIsPostRequest() )
        {
            $iUserId = Yii::app()->request->getParam('user_id');
            $oUser   = User::model()->findByPk($iUserId);

            $sDoRequest = Yii::app()->request->getParam('do');

            if ( $oUser )
            {
                if ( $sDoRequest == 'approve' )
                {
                    $sHash        = substr(md5(Yii::app()->params['password_sold'].$oUser->profile->email), 0, 8);
                    $oUser->status = 'active';
                    $oUser->save();

                    $oTariffPlan = TariffPlan::model()->findByAttributes(array
                    (
                        'user_id' => $oUser->user_id
                    ));

                    $oTariffPlan->date_start   = date('Y-m-d H:i:s');
                    $oTariffPlan->date_expired = date('Y-m-d H:i:s', strtotime('+30 day'));
                    $oTariffPlan->status  = 'approved';
                    $oTariffPlan->save();

                    Yii::app()->user->setFlash('user_approved_success', 'Пользователь утверждён.');

                    $oEmailNotification = new EmailNotification();
                    $oEmailNotification->sendEmailToUserAfterRegisterApprove($oUser, $oTariffPlan, $sHash);
                }

                if ( $sDoRequest == 'reject' )
                {
                    $oTariffPlans = TariffPlan::model()->findAllByAttributes(array
                    (
                        'user_id' => $oUser->user_id
                    ));

                    if ( $oTariffPlans )
                    {
                        foreach ( $oTariffPlans as $oUserTariffPlan )
                        {
                            $oUserTariffPlan->status = 'rejected';
                            $oUserTariffPlan->update();
                        }
                    }

                    $oUser->status = 'rejected';
                    $oUser->update();
                    Yii::app()->user->setFlash('user_rejected_success', 'Пользователь отклонен.');

                    $oEmailNotification = new EmailNotification();
                    $oEmailNotification->sendEmailToUserAfterRegisterDecline($oUser);
                }
            }

            Yii::app()->controller->redirect(Yii::app()->controller->createUrl('/admin/users/pending_list'));
        }

        $this->template->oDataProvider = User::getUsersDataProvider('pending');
    }
}